﻿using System;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules;
using DNNToolkit.CrystalReport.Components;
using System.Web.UI.WebControls;
using System.Xml;

namespace DNNToolkit.Modules.CrystalReport
{
    /// <summary>
    /// The Settings class manages Module Settings.
    /// </summary>
    public partial class Settings : ModuleSettingsBase
    {
        #region Base Method Implementations

        /// <summary>
        /// LoadSettings loads the settings from the Database and displays them.
        /// </summary>
        public override void LoadSettings()
        {
            try
            {
                if (!IsPostBack)
                {
                    LoadTextBox(Contants.KEY_Username);
                    LoadTextBox(Contants.KEY_Password);
                    LoadTextBox(Contants.KEY_Domain);
                    LoadTextBox(Contants.KEY_ReportServerUrl);
                    LoadTextBox(Contants.KEY_ReportPath);
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// <summary>
        /// UpdateSettings saves the modified settings to the Database.
        /// </summary>
        public override void UpdateSettings()
        {
            try
            {
                UpdateFromTextBox(Contants.KEY_Username);
                UpdateFromTextBox(Contants.KEY_Password);
                UpdateFromTextBox(Contants.KEY_Domain);
                UpdateFromTextBox(Contants.KEY_ReportServerUrl);
                UpdateFromTextBox(Contants.KEY_ReportPath);

                //refresh cache
                ModuleController.SynchronizeModule(ModuleId);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        #endregion
        

        private void LoadTextBox(string key)
        {
            if (TabModuleSettings[key] != null)
            {
                TextBox tb = (TextBox)FindControl(key.Replace("_", "txt"));
                tb.Text = TabModuleSettings[key].ToString();
            }
        }

        private void UpdateFromTextBox(string key)
        {
            ModuleController objModules = new ModuleController();
            TextBox tb = (TextBox)FindControl(key.Replace("_", "txt"));
            objModules.UpdateTabModuleSetting(TabModuleId, key, tb.Text);
        }

        
    }
}